package com.piece.spider.controller;

import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.module.spider.model.FlowNotice;
import com.piece.module.spider.service.FlowNoticeService;
import com.piece.module.spider.support.FlowNoticeWay;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
@Api(tags = {"爬虫通知管理"})
@RequestMapping(value = "/api/spider/notice")
public class FlowNoticeController extends FrameWorkController {

    @Resource
    private FlowNoticeService flowNoticeService;

    @RequestMapping("/load/{id}")
    @ApiOperation(value = "获取爬虫任务通知")
    @ApiImplicitParam(name="id", value = "爬虫任务通知主键", type = "path")
    public AjaxResponse load(@PathVariable Long id) {
        FlowNotice flowNotice = flowNoticeService.findById(id);
        if (null == flowNotice) {
            flowNotice = new FlowNotice();
            flowNotice.setId(id);
        }
        return success(flowNotice);
    }

    @SubmitPermission
    @PostMapping("/save")
    @ApiOperation(value = "保存爬虫任务通知")
    @ApiImplicitParam(value = "爬虫任务通知数据", dataTypeClass = FlowNotice.class, type = "body")
    public AjaxResponse save(){
        FlowNotice flowNotice = new FlowNotice();
        try {
            initDB(flowNotice);
            flowNoticeService.insert(flowNotice);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS));
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), ExceptionUtils.getStackTrace(e));
        }
    }

    @RequestMapping("/getNoticeWay")
    @ApiOperation(value = "获取流程通知方式")
    public AjaxResponse modelTable() {
        return success(FlowNoticeWay.getMap());
    }
}
